package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author ：混元太极门
 * @date ：Created in 2022年06月08日
 * @description ：
 * @version: 1.0
 */
@RequestMapping("/mobile/login")
@RestController
@Slf4j
public class MobileLoginController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MemberService memberService;

    /**
     * 登录验证
     * 请求 URL: http://localhost:17080/mobile/login/smsLogin
     * 请求方法: POST
     *
     * @return
     */
    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map map, HttpServletRequest request) {
        log.info("接收到用户登录:" + map);
        //获取手机号
        String telephone = map.get("telephone").toString();
        //获取验证码
        String validateCode = map.get("validateCode").toString();
        //找键  因为此业务是移动端登录业务
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + "_MOBILE_SIGNIN_" + telephone;
        //从redis中获取手机号和验证码
        String rediscode = redisTemplate.opsForValue().get(redisKey).toString();
        //进行比较
        if (!StringUtils.isEmpty(rediscode) && rediscode.equals(validateCode)) {
            //从Redis中删除缓存的验证码
            redisTemplate.delete(redisKey);
            //创建用户
            Member member = new Member();
            member.setPhoneNumber(telephone);//获取手机号
            member = memberService.xinxiupdate(member);
            //从session获取
            request.getSession().setAttribute("member", member);

            return new Result(true, MessageConst.LOGIN_SUCCESS);

        } else {
            return new Result(false, MessageConst.VALIDATECODE_ERROR);
        }
    }
}
